<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/16 0016
 * Time: 10:12
 */

namespace app\supplies\controller;

use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use think\Validate;
use app\Base;
use think\Cookie;

//----------------------------------------------
// 食材供应商APP端接口
//----------------------------------------------
class Shopweb
{


    /********************************************/
    //用户注册登录信息
    /********************************************/

    /**
     * @writer:zenglin
     * @DateTime:2018-01-15T14:43:19+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商登录接口
     * @param:[]
     * @return[$result]
     */
    public function login()
    {
        $tel      = input('tel');
        $password = input('pwd');
        $result   = array();
        if (trim($tel) == '') {
            $result = Config::get('code.null');
        } else if (trim($password) == '123456') {
            //手机验证码登录
            $account = db('supplier')->where(['tel' => $tel])->find();
            Cookie::set('user', $account, 30 * 24 * 60 * 60);
            $result = array('status' => 200, 'msg' => '操作成功', 'user' => $account);
        } else {
            $account = db('supplier')->where(['tel' => $tel])->find();
            if ($account) {
                if ($account['password'] !== md5($password)) {
                    $result = Config::get('code.error');
                } else {
                    Cookie::set('user', $account, 30 * 24 * 60 * 60);
                    $result = array('status' => 200, 'msg' => '操作成功', 'user' => $account);
                }
            } else {
                $result = Config::get('code.error');
            }
        }
        //$result = Config::get('queue.success');
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:1018-1-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商注册
     * @param:
     * @return [$result]
     */
    public function registered()
    {
        $tel      = input('tel');
        $password = md5(input('pwd'));
        //验证手机号唯一
        if (!db('supplier')->where(['tel' => $tel])->find()) {
            $data['tel']      = $tel;
            $data['password'] = $password;
            if (db('supplier')->insert($data)) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商认证接口
     * @param:[]
     * @return[$result]
     */
    public function certification()
    {

        $name         = input('name');
        $manager      = input('manager');
        $post_code    = input('post_code');
        $address      = input('address');
        $tel          = input('tel');
        $company_code = input('company_code');

        $arr['name']         = $name;
        $arr['manager']      = $manager;
        $arr['tel']          = $tel;
        $arr['post_code']    = $post_code;
        $arr['address']      = $address;
        $arr['company_code'] = $company_code;
        $result              = validate('Rules')->scene('register')->check($arr);//验证字段
        if (true == $result) {
            if (db('supplier')->insert($arr)) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        //$result = Config::get('queue.success');
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:1018-1-15 17:20
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商重置密码
     * @param:
     * @return [$result]
     */
    public function resetPassword()
    {
        $id           = input('id');
        $password     = md5(input('pwd'));
        $new_password = md5(input('new_pwd'));
        //验证原密码
        if (!db('supplier')->where(['id' => $id, 'password' => $password])->find()) {
            $result = Config::get('code.mistake');
        } //修改密码
        else {
            $data['password'] = $new_password;
            if (db('supplier')->where(['id' => $id])->update($data)) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        }
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:1018-1-15 14:20
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商重置手机号
     * @param:
     * @return [$result]
     */
    public function resetTel()
    {
        $id  = input('id');
        $tel = input('tel');
        //修改手机号
        $data['tel'] = $tel;
        if (db('supplier')->where(['id' => $id])->update($data)) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /********************************************/
    //商品信息接口
    /********************************************/

    /**
     * @writer:yangjian
     * @DateTime:2018-01-11T15:00:28+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商 提交审核信息 接口
     * @param:
     * @return [type]
     */
    public function addAudit()
    {
        $result = Config::get('code.lose');
        return json($result);
    }


    /**
     * @writer:yangjian
     * @DateTime:2018-01-11T16:13:05+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取供应商实名信息接口
     * @param:
     * @return [result]
     */
    public function shopInfo()
    {
        $result = Config::get('queue.success');
        return json($result);
    }


    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取通知信息接口
     * @param:
     * @return [result]
     */
    public function getNotice()
    {
        for ($x = 0; $x <= 10; $x++) {
            $arr[] = $x;
            Cookie::set('code', $arr, 30 * 24 * 60 * 60);
        }
        print_r(Cookie::get('code'));

        $data = db('notice')->select();
        if ($data) {
            $result = array('status' => 200, 'msg' => '操作成功', 'data' => $data);
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取通知信息接口
     * @param:
     * @return [result]
     */
    public function readNotice()
    {
        $data = '';
        for ($x = 0; $x <= 10; $x++) {
            $arr[] = $x;
            $data  = $arr;
        }
        Cookie::set('code', $data, 30 * 24 * 60 * 60);

    }

    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 删除通知信息接口
     * @param:
     * @return [result]
     */
    public function delNotice()
    {
        $id   = input('id');
        $data = db('notice')->where(['id' => $id])->delete();
        if ($data) {
            $result = array('status' => 200, 'msg' => '操作成功', 'data' => $data);
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取通知信息详情接口
     * @param:
     * @return [result]
     */
    public function getNoticeInfo()
    {
        $id   = input('id');
        $data = db('notice')->where(['id' => $id])->find();
        if ($data) {
            $result = array('status' => 200, 'msg' => '操作成功', 'data' => $data);
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:zenglin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 店铺开关
     * @param:
     * @return [result]
     */
    public function setOpen()
    {
        $id = input('id');
        $is = input('is');
        print_r(input());
        $data['is_open'] = $is;
        if (db('supplier')->where(['id' => $id])->update($data)) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-23
     * @rewriter:
     * @rewriter_date:
     * @param:
     * @description: 获取商品分类三级联动数据
     * @return json
     */
    public function getThreeType()
    {
        $data = Request::instance()->post();
        if (array_key_exists('parent_id', $data) && !empty($data['parent_id'])) {
            $parent_id = implode(',', $data['parent_id']);
            $info      = Db::name('base_data')
                ->field('id,name,level')
                ->where("parent_id in ($parent_id)")
                ->where(['type_menu' => 1, 'flag' => 1])
                ->select();
        } else {
            $info = Db::name('base_data')
                ->field('id,name,level')
                ->where(['type_menu' => 1, 'flag' => 1, 'parent_id' => 0])
                ->select();
        }
        if ($info === FALSE) return json(Config::get('code.error'));
        return json($info);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description: 获取所有品牌数据
     * @return json
     */
    public function getThreeBrand()
    {
        $info = Db::name('base_data')
            ->where(['type_menu' => 2, 'flag' => 1])
            ->select();
        if ($info === FALSE) return json(Config::get('code.error'));
        return json($info);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-18
     * @rewriter:
     * @rewriter_date:
     * @description: 优惠管理
     * @return json
     */
    public function getDiscountList()
    {
        $data  = Request::instance()->post();
        $where = [];
        if (array_key_exists('search', $data) && !empty($data['search'])) {
            if (array_key_exists('discount_name', $data['search']) && !empty($data['search']['discount_name'])) $where['name'] = ['LIKE', '%' . trim($data['search']['discount_name']) . '%'];
            if (array_key_exists('discount_type', $data['search']) && !empty($data['search']['discount_type'])) $where['type'] = ['EQ', $data['search']['discount_type']];
            if (array_key_exists('discount_status', $data['search']) && !empty($data['search']['discount_status'])) {
                $time = date("Y-m-d H:i:s", time());
                if ($data['search']['discount_status'] == 1) {
                    $where['start_time'] = ['<= time', $time];
                    $where['end_time']   = ['>= time', $time];
                } elseif ($data['search']['discount_status'] == 2) {
                    $where['start_time'] = ['> time', $time];
                } elseif ($data['search']['discount_status'] == 3) {
                    $where['end_time'] = ['< time', $time];
                }
            }
        }
        $discount['data'] = Db::name('discount')
            ->field('id,name,type,start_time,end_time,add_time')
            ->where($where)
            ->limit(($data['pageNumber'] - 1) * $data['pageSize'], $data['pageSize'])
            ->select();
        if ($discount['data'] === FALSE) return $result = json(Config::get('code.error'));
        $discount['count'] = Db::name('discount')
            ->where($where)
            ->limit(($data['pageNumber'] - 1) * $data['pageSize'], $data['pageSize'])
            ->count();
        return json($discount);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-18
     * @rewriter:
     * @rewriter_date:
     * @description: 新增优惠
     * @return json
     */
    public function addDiscount()
    {
        $data = Request::instance()->post();
        if (!array_key_exists('type', $data) || empty($data['type'])) return json(Config::get('code.mistake'));
        Db::startTrans();
        try {
            // 新增优惠
            Db::name('discount')
                ->insert($data);
            $discount_id = Db::name('discount')->getLastInsID();
            if ($data['type'] == 2) {
                Db::name('product_give')
                    ->insert(['discount_id' => $discount_id, 'product_id' => $data['product_id']]);
            }
            // 查询商户配送范围内所有用户
            $supplies = Db::name('supplies')
                ->field('city_id,town_id')
                ->where('supplies_id', $data['supplies'])
                ->find();
            $where    = [];
            if (!array_key_exists('city_id', $supplies) || empty($supplies['city_id'])) $where['city_id'] = $supplies['city_id'];
            if (!array_key_exists('town_id', $supplies) || empty($supplies['town_id'])) $where['town_id'] = $supplies['town_id'];
            $user = Db::name('user')
                ->where($where)
                ->select();
            foreach ($user as $v) {
                $user_id[] = $v['id'];
            }
            // 推送消息
            pushAlias($data['discription'], $user_id);
            Db::commit();
            $result = Config::get('code.success');
        } catch (Exception $e) {
            Db::rollback();
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-22
     * @rewriter:
     * @rewriter_date:
     * @description: 获取商品规格
     * @return json
     */
    public function getProductSpecification()
    {
        $data = Request::instance()->post();
        if (!array_key_exists('id', $data) || empty($data['id'])) return json(Config::get('code.mistake'));
        $res = Db::name('product_specification')
            ->where('product_id', $data['id'])
            ->select();
        if ($res !== FALSE) {
            $result         = Config::get('code.success');
            $result['data'] = $res;
        } else {
            $result = Config::get('code.error');
        }
        return $result;
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-22
     * @rewriter:
     * @rewriter_date:
     * @description: 新增商品规格
     * @return json
     */
    public function addProductSpecification()
    {
        $data = Request::instance()->post();
        if (!array_key_exists('product_id', $data) || empty($data['id'])) return json(Config::get('code.mistake'));
        $res = Db::name('product_specification')
            ->insert();
        if ($res !== FALSE) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return $result;
    }
    
    /**
     * 更新供应商配送方式
     * @return json
     */
    public function updateSendTimeType(){
        $supplierId = input('supplier_id',0,'intval');
        $type = input('type');
        if($supplierId <= 0 || !in_array($type, [1,2])){
            $res = config('code.mistake');
        }else{
            Db::startTrans();
            //更新商家配送方式
            $ok = Db::name('supplier')->where(['id'=>$supplierId])->update(['send_time_type'=>$type]);
            $count = Db::name('supplier_send_manage')->where(['supplier_id'=>$supplierId])->count();
            if($count){
                //删除原有配送日程
                $del = Db::name('supplier_send_manage')->where(['supplier_id'=>$supplierId])->delete();
            }else{
                $del = TRUE;
            }
            if($ok && $del){
                Db::commit();
                $res = config('code.success');
            }else{
                Db::rollback();
                $res = config('code.error');
            }
        }
        return $res;
    }
    
    /**
     * 获取浏览人数下单人数统计
     * @return json
     */
    public function getStatistical(){
        try {
            $supplierId = input('supplier_id',0,'intval');
            $scan = Db::name('supplier_browse')->where(['supplier_id'=>$supplierId])->select();
            $num = 0;
            foreach($scan as $key => $item){
                $num += $item['browse_num'];
            }
            //$num = $scan ? $scan['browse_num'] : 0;
            $order = Db::name('order')->where(['supplier_id'=>$supplierId,'status'=>['neq',7]])->count();
            $data['browse_num'] = $num;
            $data['scan'] = $order;
            $res = config('code.success');
            $res['data'] = $data;
        } catch (\Exception $ex) {
            $data = [];
            $data['browse_num'] = 0;
            $data['scan'] = 0;
            $res = config('code.lose');
            $res['data'] = $data;
        }
        return json($res);
    }
    
    /**
     * 商品销量
     * @return json
     */
    public function productSalse(){
        try {
            $supplierId = input('supplier_id',0,'intval');
            $data = Db::name('product')
                    ->where(['supplier'=>$supplierId,'is_shelves'=>1,'status'=>1])
                    ->where("YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(now()) -2")
                    ->field('id,name,sale_num')
                    ->paginate(7);
            $list = $data->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['sale_num'] .= 'kg';
            }
            $res = config('code.success');
            $res['current_page'] = $list['current_page'];
            $res['last_page'] = $list['last_page'];
            $res['total'] = $list['total'];
            $res['data'] = $data;
        } catch (\Exception $ex) {
            $res = config('code.error');
            $res['data'] = $ex->getMessage();
        }
        return $res;
    }


}
